import { defineStore } from 'pinia';
import { ref } from 'vue';
import axios from 'axios';
interface User {
  id: number;
  username: string;
  password: string;
  name: string;
  phoneNumber: string;
  createTime: string;
  status: string;
  description: string;
  organizationID: number;
  roleID: number;
  djid: number;
}

interface organizationID {
  id: number;
  secondaryID: number;
  organizationName: string;
  province: string;
  description: string;
}

interface Role {
  id: number;
  roleName: string;
  description: string;
  createTime: string;
}

interface Permission {
  id: number;
  firstDirectory: string;
  secondDirectory: string;
  thirdDirectory: string | null;
  permissionName: string;
  description: string;
}

export const useAuthStore = defineStore('auth', () => {
  // State
  const user = ref<User | null>(null);
  const organizationID = ref<organizationID | null>(null);
  const role = ref<Role | null>(null);
  const permissions = ref<Permission[]>([]);

  // Actions
  const setAuthData = (data: any) => {
    user.value = data.user || null;
    organizationID.value = data.organizationID || null;
    role.value = data.role || null;
    permissions.value = data.permissions || [];
  };

  const fetchAuthData = async () => {
    try {
      const response = await axios.get('/api/auth'); // 替换为实际的接口地址
      setAuthData(response.data);
    } catch (error) {
      console.error('Failed to fetch auth data:', error);
    }
  };

  const clearAuthData = () => {
    user.value = null;
    organizationID.value = null;
    role.value = null;
    permissions.value = [];
  };
  const logout = () => {
    clearAuthData(); // 清理 Pinia 仓库
    localStorage.clear(); // 清理本地存储
  };

  return {
    user,
    organizationID,
    role,
    permissions,
    setAuthData,
    fetchAuthData,
    clearAuthData,
    logout,
  };
}, {
  persist: {
    enabled: true,
  } as any
});
